package main.java.com.dou.week01;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author dsp
 * @date 2021-03-19
 */
public class MyClassLoader extends  ClassLoader{

    /**
     * 加载文件后需要解码
     *
     * @param name
     * @return
     */
    @Override
    protected Class<?> findClass(String name) {
        byte[] bytes = new byte[0];
        try {
            bytes = Files.readAllBytes(Paths.get(name));
            bytes = decode(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return defineClass("Hello" ,bytes, 0, bytes.length);
    }

    public static byte[] decode(byte[] bytes){
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) (255-bytes[i]);
        }
        return bytes;
    }

    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class<?> clazz = new MyClassLoader().findClass("week01/Hello.xlass").newInstance().getClass();
        Method method = clazz.getMethod("hello");
        method.invoke(clazz.newInstance());
    }
}
